<!-- eslint-disable no-template-curly-in-string -->
<!--
 * @Author       : wfl
 * @LastEditors: fj
 * @description  :
 * @updateInfo   :
 * @Date         : 2023-07-26 18:38:37
 * @LastEditTime: 2023-08-10 18:08:09
-->
<script lang="ts" setup name="SystemChannel">
import type { FormInstance } from 'element-plus'
import IkingTemplateInset from 'iking-template-inset'
import 'iking-template-inset/dist/style.css'
import { useChannel } from './useChannel'
import { msgApi } from '@/MainApp/apis/msg'

const props = defineProps({
  data: {
    type: Object,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  },
  // sys----系统     sms----短信
  flag: {
    type: String,
    default: ''
  }
})

const emits = defineEmits<{
  (e: 'close'): void
  (e: 'success'): void
}>()

const injectTepForm: Ref<any> | undefined = inject('tempForm')
const { lenContent } = useLength()
const systemForm = computed(() => {
  if (!props.data?.id) {
    props.data.voice = false
    props.data.templateId = props.data.templateId || injectTepForm?.value?.id
  }
  props.data.supportTemplate = false
  return props.data
})

const { loading, handSaveUnnable, handEnable, handCancel, msgError, linkHolder, linkRule }
  = useChannel(props.isEdit, systemForm)

const validError = ref(false)
const systemFormRef: Ref<FormInstance | null> = ref(null)
const tempRef: Ref<{ clearValue: Function; } | null> = ref(null)
const list: Ref<any> = ref([])
const rules = {
  content: [
    {
      required: true,
      trigger: 'change',
      validator: (rule: any, val: string, cb: Function) => {
        if (!val || !val.replace(/&nbsp;/g, ''))
          cb('请配置消息参数')

        else
          cb()
      }
    }
  ]
}

onMounted(() => {
  if (props.flag === 'sms')
    getList()
})
// 短信时获取下拉数据
const getList = async () => {
  const { msg, data, success } = await msgApi.getSmsTemplateList({
    supportTemplate: false
  })
  if (!success)
    msgError(msg)
  list.value = data || []
}

const handOrigional = (val: string) => {
  systemForm.value.content = val
}

const cancel = () => {
  systemFormRef.value?.resetFields()
  tempRef.value?.clearValue()
  emits('close')
}

const handValidateForm = (fn: Function) => {
  systemFormRef.value?.validate((valid: boolean) => {
    valid && fn((success: boolean) => success && emits('success'))
    validError.value = !valid
  })
}
</script>

<template>
  <el-form
    ref="systemFormRef"
    v-loading="loading"
    label-width="100px"
    :model="systemForm"
    label-position="top"
    :rules="rules"
  >
    <!-- 短信时显示 -->
    <IkFormItemTitle
      v-if="flag === 'sms'"
      label="短信平台"
      prop="channelId"
      title="（点击参数名称，将参数插入消息内容）"
    >
      <el-select v-model="systemForm.channelId" placeholder="请选择短信平台">
        <el-option
          v-for="item in list"
          :key="item.smsId"
          :label="item.name"
          :value="item.smsId"
        />
      </el-select>
    </IkFormItemTitle>
    <IkFormItemTitle
      label="参数列表"
      prop="content"
      title="（点击参数名称，将参数插入消息内容）"
    >
      <IkingTemplateInset
        ref="tempRef"
        :template="systemForm.content || ''"
        :valid-error="validError"
        placeholder="请输入内容或点击左侧参数项插入参数"
        :list="systemForm.paramDefinitions"
        :param-props="{ name: 'paramDescription', key: 'paramName' }"
        @change="handOrigional"
      />
    </IkFormItemTitle>
    <IkFormItemTitle
      v-if="isEdit && systemForm.id && systemForm.redirectDefinitions?.[0]"
      label="跳转链接"
      prop="redirectDefinitions[0].redirectTo"
      title="（点击消息后的跳转链接）"
      :rules="linkRule"
    >
      <el-input
        v-model.trim="systemForm.redirectDefinitions[0].redirectTo"
        :max-length="lenContent"
        :placeholder="linkHolder"
      />
    </IkFormItemTitle>
    <IkFormItemTitle
      v-else
      label="跳转链接"
      prop="redirectDefinitions"
      title="（点击消息后的跳转链接）"
      :rules="linkRule"
    >
      <el-input
        v-model.trim="systemForm.redirectDefinitions"
        :max-length="lenContent"
        :placeholder="linkHolder"
      />
    </IkFormItemTitle>
    <el-form-item label="系统消息是否播放语音" prop="voice">
      <el-switch
        v-model="systemForm.voice"
        inline-prompt
        :active-value="true"
        :inactive-value="false"
        active-text="播放"
        inactive-text="不播放"
      />
    </el-form-item>
    <el-form-item v-if="!isEdit" label="" class="ik-msg-channel">
      <el-button type="primary" text @click="handValidateForm(handEnable)">
        启用
      </el-button>
      <el-button type="primary" text @click="handValidateForm(handSaveUnnable)">
        保存不启用
      </el-button>
      <el-button text @click="cancel()">取消</el-button>
    </el-form-item>
  </el-form>
  <IkPageFooter v-if="isEdit">
    <el-button @click="handCancel()">取消</el-button>
    <el-button
      type="primary"
      @click="handValidateForm(handSaveUnnable)"
    >
      保存不启用
    </el-button>
    <el-button
      type="primary"
      @click="handValidateForm(handEnable)"
    >
      启用
    </el-button>
  </IkPageFooter>
</template>

<style lang="scss" scoped>
.ik-msg-channel {
  :deep(.el-form-item__content) {
    justify-content: end;
  }
}
</style>
